package com.dhms.vostok1.service.net


import com.dhms.vostok1.data.*
import com.dhms.vostok1.data.maintenance.LubricationTaskData
import com.dhms.vostok1.data.spot_patrol.*
import com.dhms.vostok1.network.BaseNetworkApi
import com.dhms.vostok1.network.MoshiObject
import com.dhms.vostok1.network.MoshiObject.moshi
import com.dhms.vostok1.utils.toMap
import com.squareup.moshi.JsonAdapter
import io.realm.kotlin.ext.realmListOf
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Converter
import retrofit2.Response
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.Body
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.QueryMap

/**
 * 网络请求具体实现
 */
object NetworkApi : BaseNetworkApi<INetworkApi>() {
    var token: String? = null
    var organizationId: Long? = null
    var userId: Long? = null

    /*登录*/
    suspend fun login(@Body body: LoginReqBody): Response<LoginResData> {
        return service.login(body)
    }

    /*短信登录*/
    suspend fun messageLogin(@Body body: MessageLoginReqBody): Response<LoginResData> {
        return service.messageLogin(body)
    }

    /*获取登录用户信息*/
    suspend fun getUserInfo() = getResult {
        service.getUserInfo()
    }

    /*获取用户Customer信息*/
    suspend fun getCustomerInfo() = getResult {
        service.getCustomerInfo()
    }

    /*发送验证码*/
    suspend fun sendVerifyCode(@Body body: VerifyCodeReqBody) = getResult {
        service.sendVerifyCode(body)
    }

    /*检查验证码*/
    suspend fun checkVerifyCode(@Body body: CheckVerifyCodeReqBody) = getResult {
        service.checkVerifyCode(body)
    }

    /*重置密码*/
    suspend fun resetPassword(@Body body: ResetPasswordReqBody) = getResult {
        service.resetPassword(body)
    }

    /*获取异常记录列表*/
    suspend fun getAbnormalRecords() = getResult {
        service.getAbnormalRecords()
    }

    /*获取设备目录*/
    suspend fun getDeviceCategory() = getResult {
        service.getDeviceCategory()
    }

    /*获取公司下的所有分类设备*/
    suspend fun getCategoryDevices() = getResult {
        service.getCategoryDevices()
    }

    /**
     * Device Center
     */
    // 获取设备列表
    suspend fun getDeviceList(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getDeviceList(query)
    }

    // 获取设备检测参数列表
    suspend fun getDeviceMonitorInfo(
        @Path("de_id") deId: String
    ) = getResult {
        service.getDeviceMonitorInfo(deId)
    }

    // 获取设备检测参数列表
    suspend fun getDeviceDynamicMonitorInfo(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getDeviceDynamicMonitorInfo(query)
    }

    // 获取设备状态统计数据
    suspend fun getDeviceStateStatisticData() =
        getResult {
            service.getDeviceStateStatisticData()
        }

    /*设备详情*/
    suspend fun getDeviceDetail(
        @Query("de_id") de_id: Long
    ) = getResult {
        service.getDeviceDetail(de_id)
    }

    /**
     * Fault List
     */
    suspend fun getFaultList(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getFaultList(query)
    }

    /*告警处理*/
    suspend fun sendFaultProcess(@Body body: FaultProcessReqBody) = getResult {
        service.sendFaultProcess(body)
    }

    /* 告警等级 */
    suspend fun getFaultLevelList() = getResult {
        service.getFaultLevelList()
    }

    /* 告警统计数据 */
    suspend fun getFaultStatisticData(
        @QueryMap queryMap: Map<String, String>,
        @Query("state[]") state1: String,
        @Query("state[]") state2: String,
        @Query("state[]") state3: String,
        @Query("usetypes[]") userType1: String,
        @Query("usetypes[]") userType2: String,
    ) = getResult {
        service.getFaultStatisticData(queryMap, state1, state2, state3, userType1, userType2)
    }

    /**
     * Fault detail
     */
    suspend fun getFaultDetail(
        @Query("fa_id") fault_id: Long
    ) = getResult {
        service.getFaultDetail(fault_id)
    }

    /**
     * Fault diagnose
     */
    suspend fun getFaultDiagnoseInfo(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getFaultDiagnoseInfo(query)
    }

    /**
     * Related fault
     */
    suspend fun getRelatedFaults(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getRelatedFaults(query)
    }


    suspend fun getTopLevelCategory() = getResult {
        service.getTopLevelCategory()
    }

    suspend fun getFaultTypes(@QueryMap query: Map<String, Long>) = getResult {
        service.getFaultTypes(query)
    }

    /**
     * 点巡检
     */
    /**
     * offset: 当前页码
     * limit: 单页条数
     * query_task_type: 查询任务类型 null: 全部 , PlanType
     * query_task_status: 查询任务状态 null: 全部, TaskStatus
     */
    suspend fun getTaskGroups(
        @Query("offset") offset: Int?,
        @Query("limit") limit: Int? = 10,
        @Query("query_task_type") query_task_type: List<PlanType>? = null,
        @Query("query_task_status") query_task_status: List<TaskStatus>? = null,
        @Query("end_time_greater") end_time_greater: Long? = null,
        @Query("is_remove_complete") is_remove_complete: Boolean? = false,
    ) = getResult {
        val taskType = query_task_type?.map { it.code }.toString()
        val taskStatus = query_task_status?.map { it.code }.toString()

        service.getTaskGroups(
            offset,
            limit,
            taskType,
            taskStatus,
            end_time_greater,
            is_remove_complete
        )
    }

    /*查询任务详情*/
    suspend fun getTaskDetail(
        @Path("group_id") group_id: String,
        @Path("task_id") task_id: Long
    ) = getResult {
        service.getTaskDetail(group_id, task_id)
    }

    /*更新任务*/
    suspend fun updateTask(@Body body: TaskUpdateReqBody) = getResult {
        val jsonAdapter: JsonAdapter<TaskUpdateReqBody> =
            moshi.adapter<TaskUpdateReqBody>(TaskUpdateReqBody::class.java)
        val json: String = jsonAdapter.toJson(body)
        val b = jsonAdapter.fromJson(json)
        b?.deTreeChartConfig = null
        b?.patrolItems?.spotDetector?.forEach {
            it.vibData = realmListOf()
        }

        service.updateTask(b ?: body)
    }

    /*批量更新任务组中的执行人*/
    suspend fun updateGroupExecutors(
        @Path("group_id") group_id: String,
        @Body body: TaskExecutorsReqBody
    ) = getResult {
        service.updateGroupExecutors(group_id, body)
    }

    /*查询任务组详情*/
    suspend fun getTaskGroupDetail(@Path("group_id") group_id: String) = getResult {
        service.getTaskGroupDetail(group_id)
    }

    /* 获取任务列表 */
    suspend fun getTaskList(
        @QueryMap query: Map<String, String>
    ) = getResult {
        service.getTaskList(query)
    }

    /*异常记录条目*/
    suspend fun getAbnormalItemList(body: AbnormalsReqBody) = getResult {
        service.getAbnormalItemList(
            body.page,
            body.per_page,
            body.start_time,
            body.end_time,
            body.device_ids,
            body.status,
            body.source
        )
    }

    /*异常上报*/
    suspend fun createAbnormalItem(@Body body: AbnormalsCreateReqBody) = getResult {
        service.createAbnormalItem(body)
    }

    /*异常记录详情*/
    suspend fun getAbnormalDetail(@Path("id") id: String) = getResult {
        service.getAbnormalDetail(id)
    }

    /*更新异常处理*/
    suspend fun updateAbnormalDetail(
        @Path("id") id: String,
        @Body body: AbnormalsUpdateReqBody
    ) = getResult {
        service.updateAbnormalDetail(id, body)
    }

    /*点检异常查询*/
    suspend fun getAbnormalItems(
        @Query("page") page: Int,
        @Query("per_page") per_page: Int = 40,
    ) = getResult {
        service.getAbnormalItems(page, per_page)
    }

    /*点检异常项添加*/
    suspend fun createAbnormalItems(
        @Body body: AbnormalItemsReqBody
    ) = getResult {
        service.createAbnormalItems(body)
    }

    /*点检异常项删除*/
    suspend fun deleteAbnormalItems(
        @Path("id") id: String,
    ) = getResult {
        service.deleteAbnormalItems(id)
    }

    // ============== 通用接口 ================
    /**
     * TSDB
     */
    suspend fun getTSDBData(
        @Body body: TSDBReqBody
    ) = getResult {
        service.getTSDBData(body)
    }

    /**
     * OSS
     */
    suspend fun uploadFileToOSS(requestBody: RequestBody, fileName: String) = getResult {
        val body =
            MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("bucket", "dhms")
                .addFormDataPart("rename", "no")
                .addFormDataPart("part_name", "upload")
                .addFormDataPart("file", fileName, requestBody).build()
        service.uploadFileToOSS(body)
    }

    /*
    * Lubrication
    * */

    /*润滑任务列表*/
    suspend fun getLubricationTaskItems(@QueryMap query: Map<String, String>) = getResult {
        service.getLubricationTaskItems(query)
    }

    /*润滑任务详情*/
    suspend fun getLubricationTaskDetail(@Path("task_id") taskId: String) = getResult {
        service.getLubricationTaskDetail(taskId)
    }

    /*更新润滑任务*/
    suspend fun updateLubricationTaskDetail(@Body body: LubricationTaskData) = getResult {
        service.updateLubricationTaskDetail(body)
    }


    /*
    * Maintenance
    * */

    suspend fun getMaintenanceTaskItems(@QueryMap query: Map<String, String>) = getResult {
        service.getMaintenanceTaskItems(query)
    }

    suspend fun getMaintenanceTaskDetail(@Path("task_id") taskId: String) = getResult {
        service.getMaintenanceTaskDetail(taskId)
    }

    suspend fun updateMaintenanceTaskDetail(@Body body: LubricationTaskData) = getResult {
        service.updateMaintenanceTaskDetail(body)
    }

    suspend fun getRepairTaskList(@QueryMap query: Map<String, String>) = getResult {
        service.getRepairTaskList(query)
    }

    /**
     * Message Center
     */

    suspend fun getMessageCenterUnread() = getResult {
        service.getMessageCenterUnread()
    }

    suspend fun getMessageUnReadCount() = getResult {
        service.getMessageUnReadCount()
    }

    suspend fun getMessageCenterList(@QueryMap query: Map<String, String>) = getResult {
        service.getMessageCenterList(query)
    }

    suspend fun messageIsRead(@Path("message_id") messageId: Int) = getResult {
        service.messageIsRead(messageId)
    }

    /**
     * 点检仪数据上报
     */
    // 上传设备信息
    suspend fun uploadTerminalInfo(@Body body: ReportTerminalInfo) = getResult {
        service.uploadTerminalInfo(body)
    }

    // 上传采集参数
    suspend fun uploadTerminalTSData(@Body body: ReportTsData) = getResult {
        service.uploadTerminalTSData(body)
    }

    // 上传震动数据
    suspend fun uploadTerminalBlockData(@Body body: ReportBlockData) = getResult {
        service.uploadTerminalBlockData(body)
    }

    /**
     * 隐患与故障
     */
    suspend fun getDangerList(@QueryMap query: Map<String, String>) = getResult {
        service.getDangerList(query)
    }

    suspend fun getDangersAndFaultsCount() = getResult {
        service.getDangersAndFaultsCount()
    }

    /*
     * Check Instrument Speed Relationships
     */
    suspend fun getCheckInstrumentSpeedSheetData() = getResult {
        service.getCheckInstrumentSpeedSheetData()
    }

    /**
     * 振动分析
     */
    suspend fun vibAnalyse(@Body body: VibAnalyseReqBody): Response<Any> {
        return service.vibAnalyse(body)
    }

    /**
     * 物联固件查询
     */
    suspend fun getFirmwares(query: FirmwaresReqQuery) = getResult {
        service.getFirmwares(query.toMap()!!)
    }

    /**
     * 获取公司层级信息
     */
    suspend fun getCompanyGroup() = getResult {
        service.getCompanyGroup()
    }

    /**
     * 获取公司员工
     */
    suspend fun getMember(id: String, view_sub_org: String? = null, keyword: String? = null) =
        getResult {
            service.getMember(id, view_sub_org, keyword)
        }

    /**
     * 今天待办数量
     */
    suspend fun getToDoStatistics() = getResult {
        service.getToDoStatistics()
    }

    /**待办 数据 列表*/
    suspend fun getToDoCenterList(@QueryMap query: Map<String, String>) = getResult {
        service.getToDoCenterList(query)
    }

    /**获取 设备各测点 隐患/故障*/
    suspend fun getDamageStatisticDevice(@Path("device_id") deviceId: Long) = getResult {
        service.getDamageStatisticDevice(deviceId)
    }

    override fun initFactory(): Converter.Factory = MoshiConverterFactory.create(MoshiObject.moshi)

}

